<?php
session_start();
    
    // Created By : Julian Ponce
    // B.S. Computer Science - De La Salle Canlubang
    // September 27, 2011
    // IN PARAMETERS : documentId, documentType, senderId
    // 
    // This AJAX Request records the receiving action to the database.
    // This is used in viewPageReceiving.php
 
// Start - Checker for those users who will just go to the page by typing directly in the url.
if ($_POST) {
    //LOAD PRE-DEFINED VARIABLES FOR DATABASE ACCESS
//    include('../includes/siteConfig.php');
     
    $hostName = "localhost";
    $rootName = "dbasegr";
    $dBasePassword = "dbgr2012";
    $dBaseName = 'greenroute';
    
    // CONNECT TO DATABASE
    $connect = mysql_connect($hostName,$rootName,$dBasePassword) or die ('Unable to connect!');
    mysql_select_db($dBaseName) or die ('Unable to select database!');

    // GET VARIABLES VIA POST METHOD
    $documentId = $_POST['documentId'];
    $senderId = $_POST['senderId'];
    $rcvdAttachmentsArray = $_POST['rcvdAttachmentsArray'];
    $attachmentCount = $_POST['attachmentCount'];
   
    
    //VARIABLE USED IN ORDER TO DETERMINE IF THE MAIN DOCUMENT STATUS = PENDING or RECEIVED.
    $attachmentsComplete = 1;
    
    //SPLIT THE ARRAY OF ATTACHMENT ID's
    if ($attachmentCount == 1 ) {
        $attachmentContainer[0] = $rcvdAttachmentsArray;
    }
    else if ($attachmentCount > 1) {
        $attachmentContainer = explode(",", $rcvdAttachmentsArray);
    }   
    
    
    if ($attachmentCount >= 0) {    
        // GET THE LOGGED USER
        $loggedUserId = $_SESSION['loggedUserId'];

        //GET THE CURRENT DATE TIME
        date_default_timezone_set('Asia/Singapore');
        $currentDateTime= date("Y-m-d H:i:s" , time());


        //GET CURRENT STEP ID BASED ON MAIN DOCUMENT.
        $query = 
            "
                SELECT currentStepId
                FROM MainDocument
                WHERE mainDocumentId = '$documentId'
            ";
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result);
        $currentStepId = $row['currentStepId'];
        
        //GET PREVIOUS STEP ID BASED ON LOGS OF MAIN DOCUMENT.
        $query = 
            "
                SELECT *
                FROM Log
                WHERE documentId = '$documentId' and activity = 'Sent'
                ORDER BY logDateTime DESC
            ";
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result);
        $prevStepId = $row['stepId'];
        $prevLogDateTime = $row['logDateTime'];
        
        
        error_log("docId = $documentId , sender = $senderId, prevId = $prevStepId");

        // GET ALL ATTACHMENTS OF THE MAIN DOCUMENT
        $query = 
            "
                SELECT attachmentId
                FROM Attachment, Log
                WHERE Attachment.mainDocumentId = '$documentId' AND Attachment.location = '$senderId' AND
                      Log.stepId = '$prevStepId' AND Log.activity = 'Sent' AND Attachment.attachmentId = Log.documentId AND
                      Log.logDateTime = '$prevLogDateTime'
            ";
        $attachmentResults = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        
        error_log("------------ITERATION START----------");
        //ITERATE ALL ATTACHMENTS AND CHANGE ITS LOCATION. IN EACH ITERATE, SAVE THE CORRESPONDING LOG IN LOG TABLE
        while ($attachmentRows = mysql_fetch_array($attachmentResults)) {
            $tempAttachmentId = $attachmentRows['attachmentId'];
            $attachmentFound = 0;

            for ($tempCounter = 0; $tempCounter < $attachmentCount && !$attachmentFound; $tempCounter++) {                
                if ($tempAttachmentId == $attachmentContainer[$tempCounter]) {
                    $attachmentFound=1;      
                }
            } // END OF FOR-LOOP

            
            if ($attachmentFound) {
                //CHANGE LOCATION OF ATTACHMENT TO LOGGED USER.
                $query = 
                    "
                        UPDATE Attachment
                        SET location = '$loggedUserId'
                        WHERE attachmentId = '$tempAttachmentId'
                    ";
                 mysql_query($query);

                // SAVE THE ACTIVITY TO LOG TABLE (RECEIVED)
                $query = 
                    "
                        INSERT INTO Log (documentId, userId, stepId, logDateTime, activity)
                        VALUES ('$tempAttachmentId', '$loggedUserId', '$currentStepId', '$currentDateTime', 'Received')
                    ";
               mysql_query($query);
            }

            
            else {
                // MAIN DOCUMENTS ATTACHMENT ISN'T COMLETE.
                $attachmentsComplete = 0;
                
                //CHECKS IF THE ATTACHMEND ID IS ALREADY PENDING
                $query = 
                    "
                        SELECT activity
                        FROM Log
                        WHERE documentId = '$tempAttachmentId'
                        ORDER BY logDateTime DESC
                    ";
                $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
                $row = mysql_fetch_array($result);


                if ($row['activity'] != "Pending") {
                    // SAVE THE ACTIVITY TO LOG TABLE (PENDING)
                    $query = 
                        "
                            INSERT INTO Log (documentId, userId, stepId, logDateTime, activity)
                            VALUES ('$tempAttachmentId', '$loggedUserId', '$currentStepId', '$currentDateTime', 'Pending')
                        ";
                    mysql_query($query);
                }
            } // END OF ELSE (ATTACHMENT NOT FOUND)
        } // END OF WHILE (ITERATION OF ALL ATTACHMENTS)
        
        // VERIFIES IF ATTACHMENT IS COMPLETE OR NOT.
        // If compelte, main document action = Received.
        if ($attachmentsComplete) {
            $query = 
                "
                    UPDATE MainDocument
                    SET action = 'Received'
                    WHERE mainDocumentId = '$documentId'
                ";
             mysql_query($query);
        } 
        
        // Else If not compelte, main document action = Pending.
        else {
            $query = 
                "
                    UPDATE MainDocument
                    SET action = 'Pending'
                    WHERE mainDocumentId = '$documentId'
                ";
             mysql_query($query);
        }
        // END OF CHECKING IF ALL ATTACHMENTS ARE COMPLETE
    }// END OF IF ATTACHMENT COUNT > 0
    
    
    json_encode(1);
    mysql_close($connect);
}   // End - Checker for those users who will just go to the page by typing directly in the url.
else {
    date_default_timezone_set('Asia/Singapore');
        $currentDateTime= date("Y-m-d H:i:s" , time());
 echo "You are not authorized to view this page. This incident will be reported immediately.";
 echo "CURRENT DATE TIME > $currentDateTime";
}
?>